<?php
class WSubscriptionAdminUpdateNewsletter extends UFormWorklet
{
	public $modelClassName = 'MSubscriptionCampaignForm';
	public $primaryKey = 'id';
	
	public function accessRules()
	{
		return array(
			array('allow', 'roles' => array('administrator')),
			array('deny', 'users'=>array('*'))
		);
	}
	
	public function title()
	{
		return $this->isNewRecord
			? $this->t('Create Newsletter')
			: $this->t('Update Newsletter');
	}
	
	public function properties()
	{
		return array(
			'elements' => array(
				'listsField' => array(
					'type' => 'checkboxlist',
					'items' => $this->lists(),
					'layout' => "{label}\n<fieldset>{input}\n{hint}</fieldset>",
				),
				'scheduleField' => array('type' => 'UDateTimePicker', 'htmlOptions'=>array('class'=>'medium')),
				'subject' => array('type' => 'text'),
				'plainBody' => array('type' => 'textarea'),
				'htmlBody' => array('type' => 'UCKEditor',
					'layout' => "<div class='clearfix'>{label}</div>{input}\n{hint}"),
			),
			'buttons' => array(
				'submit' => array('type' => 'submit',
					'label' => $this->isNewRecord?$this->t('Create'):$this->t('Update'))
			),
			'model' => $this->model
		);
	}
	
	public function taskSave()
	{
		$data = $this->model->attributes;
		$data['schedule'] = UTimestamp::applyGMT($this->model->scheduleField,param('timeZone'));
		$data['lists'] = is_array($this->model->listsField)
			? $this->model->listsField
			: array();
		foreach($data['lists'] as $l)
		{
			$list = wm()->get('subscription.helper')->list($l);
			if($list->type == 100)
			{
				$data['lists'] = array($l);
				break;
			}
		}
		wm()->get('subscription.helper')->addCampaign($data);
	}
	
	public function taskRenderOutput()
	{
		cs()->registerScript(__CLASS__,'jQuery("#wlt-BaseDialog").dialog("option", "width", 1000);');
		parent::taskRenderOutput();
	}
	
	public function taskLists()
	{
		return CHtml::listData(MSubscriptionList::model()->findAll(new CDbCriteria(array(
			'order' => 'title ASC',
		))),'id','title');
	}
	
	public function ajaxSuccess()
	{
		$list = wm()->get('subscription.admin.newsletters');
		wm()->get('base.init')->addToJson(array(
			'content' => array(
				'append' => CHtml::script('$.fn.yiiGridView.update("' .$list->getDOMId(). '-grid");
					$.uniprogy.dialogClose();'),
			)
		));
	}
}